package com.example.xd.default_call

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.xd.default_call.Global_Val.Companion.CALL_IN
import com.example.xd.default_call.Global_Val.Companion.CALL_OUT
import com.example.xd.default_call.Global_Val.Companion.CALL_VIDEO_IN
import com.example.xd.default_call.Global_Val.Companion.CALL_VIDEO_OUT
import com.example.xd.default_call.eventbus_msg.InitFragmentMsg
import com.example.xd.default_call.eventbus_msg.MultCallInMsg
import com.example.xd.default_call.fragment.BaseFragment
import com.example.xd.default_call.fragment.FragmentFactory
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class UIActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_u_i)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun initFirstFG(msg: InitFragmentMsg) {
        val type = msg.type
        when (type) {
            CALL_IN -> {
                currentFg = FragmentFactory.getFragment(CALL_IN)
            }
            CALL_OUT -> {
                currentFg = FragmentFactory.getFragment(CALL_OUT)
            }
            CALL_VIDEO_IN -> {
                currentFg = FragmentFactory.getFragment(CALL_VIDEO_IN)
            }
            CALL_VIDEO_OUT -> {
                currentFg = FragmentFactory.getFragment(CALL_VIDEO_OUT)
            }
        }
        if (!currentFg.isAdded) {
            supportFragmentManager.beginTransaction().add(R.id.fl, currentFg).commit()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun multcall(msg: MultCallInMsg) {
        switchFragment(currentFg, FragmentFactory.getFragment(msg.multCallIn))
    }

    lateinit var currentFg: BaseFragment

    fun switchFragment(from: BaseFragment, to: BaseFragment) {
        if (from == null || to == null || from == to) {
            return
        }
        val beginTransaction = supportFragmentManager.beginTransaction()
        if (!to.isAdded) {
            beginTransaction.hide(from).add(R.id.fl, to).commit()
        } else {
            beginTransaction.hide(from).show(to).commit()
        }
        currentFg = to
    }
}